clear,clc;
clear all;
numIter =10;
conf = 3;
confidence_percent = conf;

path_origdata = '/home/liang/Projects/ASD_QC/DataProcessed/rest';
ListPath = '/home/liang/Projects/ASD_QC/Lists';
outputDIR = '/home/liang/Projects/ASD_QC/Results';
templateDIR = '/home/liang/Projects/ASD_QC/Parcellation_template';
scriptDIR = '/home/liang/Projects/ASD_QC/Results';

data_type = 'ASD'
symbol = 'OHSU'

SIDs = textread([ListPath '/censored_sub_list_' data_type '_' symbol '.txt'],'%s');

eval(['!mkdir ' outputDIR '/Variability']);

res_lh_corr = [];
res_rh_corr = [];
%%%%%%%%%%%%%%%%%%%%

res = [];
for s = 1:length(SIDs)
    fprintf(['[step]: ' num2str(s) ' start \n']);

    sid = SIDs{s};

    sess_files = dir([scriptDIR '/FC_mats/' symbol '/' sid '*']);

    sub_res = [];
    for n = 1:length(sess_files)
        src_sess_data = load([scriptDIR '/FC_mats/' symbol '/' sess_files(n).name])

        for m = 1:length(sess_files)
            if n~=m
                des_sess_data = load([scriptDIR '/FC_mats/' symbol '/' sess_files(m).name])

                C_res = func_matcorr(src_sess_data.fc, des_sess_data.fc);

                C_res(isnan(C_res)) = 0.0;

                sub_res = [sub_res; C_res];
            end
        end
    end

    sub_res = mean(sub_res, 1);
    res = [res; sub_res];

    fprintf(['[step]: ' num2str(s) ' finished \n']);
end

res = nanmean(res, 1);
res(isnan(res)) = 0.0;
res = 1 - res;
fprintf('done');


lh = res(:, 1:2562)'
rh = res(:, 2563:5124)'
save([outputDIR '/Variability/intra_Variability_FS4_' data_type '_' symbol '.mat'], 'lh', 'rh')

exclude_lh_template = [templateDIR '/lh_network_1_asym_fs4.mgh']
exclude_rh_template = [templateDIR '/rh_network_1_asym_fs4.mgh']
[lh_vol, M, mr_parms, volsz] = load_mgh(exclude_lh_template);
[rh_vol, M, mr_parms, volsz] = load_mgh(exclude_rh_template);

tem_lh = lh;
tem_rh = rh;

tem_lh(find(lh_vol == 1)) = 0.0;
tem_rh(find(rh_vol == 1)) = 0.0;

save_mgh(tem_lh, [outputDIR '/Variability/' 'lh_' data_type '_' symbol '_fs4_intra_variability.mgh'], eye(4));
save_mgh(tem_rh, [outputDIR '/Variability/' 'rh_' data_type '_' symbol '_fs4_intra_variability.mgh'], eye(4));
